// src/router/index.js
import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/stores/userinfo'


const routes = [
  {
    path: '/',
    // 重定向到首页
    redirect: '/home'

  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/home.vue'),
    meta: {
      showTabbar: true
    }
  },
  {
    path: '/follow', name: 'follow', component: () => import('@/views/follow.vue'),
    meta: {
      showTabbar: true,
      requiresAuth: true
    }
  },
  {
    path: '/message', name: 'message', component: () => import('@/views/message.vue'),
    meta: {
      showTabbar: true,
      requiresAuth: true
    }
  },
  {
    path: '/my', name: 'my', component: () => import('@/views/my.vue'),
    meta: {
      showTabbar: true,
      requiresAuth: true
    }
  },
  {
    path: '/release', name: 'release', component: () => import('@/views/release.vue'),
    meta: {
      requiresAuth: true
    }
  },
  // 消息/评论页
  { path: '/message/comment', name: 'Commentpage', component: () => import('@/views/message/Commentpage.vue'), meta: { requiresAuth: true } },
  // 消息/点赞页
  { path: '/message/like', name: 'Likepage', component: () => import('@/views/message/Likepage.vue'), meta: { requiresAuth: true } },
  // 消息/关注页
  { path: '/message/fan', name: 'Fanpage', component: () => import('@/views/message/Fanpage.vue'), meta: { requiresAuth: true } },
  // 消息/@我的页
  { path: '/message/my', name: 'mypage', component: () => import('@/views/message/Mypage.vue'), meta: { requiresAuth: true } },
  // 消息/联系客服页
  { path: '/message/contact', name: 'Contact', component: () => import('@/views/message/Contact.vue'), meta: { requiresAuth: true } },
  // 聊天室
  { path: '/chatroom/:userId?', name: 'Chat', component: () => import('@/components/common/ChatRoom.vue'), meta: { requiresAuth: true } },
  // 搜索页
  { path: '/search', name: 'search', component: () => import('@/views/home/search.vue') },
  // 好友首页
  { path: '/friends', name: 'friends', component: () => import('@/components/common/FriendsHomepage.vue') },
  // 我的关注
  { path: '/my/followings', name: 'MyFollowings', component: () => import('@/views/my/Myfollowings.vue'), meta: { requiresAuth: true } },
  // 我的粉丝
  { path: '/my/fans', name: 'MyFans', component: () => import('@/views/my/myfans.vue'), meta: { requiresAuth: true } },
  //  TA关注的列表
  { path: '/friends/followings', name: 'TAFollowings', component: () => import('@/components/common/TAsfocus.vue'), meta: { requiresAuth: true } },
  //  TA粉丝的列表
  { path: '/friends/fans', name: 'TAFans', component: () => import('@/components/common/TAsfans.vue'), meta: { requiresAuth: true } }

]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 }
  }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  console.log('路由导航:', from.path, '->', to.path)

  // 添加错误处理，防止路由守卫中的错误导致白屏
  try {
    const userStore = useUserStore()
    const isLoggedIn = !!userStore?.userInfo?.userId

    console.log('用户登录状态:', isLoggedIn)

    // 检查路由是否需要登录
    if (to.meta.requiresAuth && !isLoggedIn) {
      console.log('路由需要登录但用户未登录，显示登录弹窗')

      // 如果需要登录但用户未登录，不进行路由跳转
      // 而是通过事件总线触发登录弹窗
      next(false)

      // 保存目标路径，登录后可以重定向
      const redirectPath = to.fullPath

      // 将目标路径保存到会话存储中
      if (typeof window !== 'undefined' && window.sessionStorage) {
        sessionStorage.setItem('intendedPath', redirectPath)
      }

      // 触发全局事件显示登录弹窗，并传递重定向路径
      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('show-login', {
          detail: { redirect: redirectPath }
        }))
      }
      return
    }

    console.log('路由导航允许')
    next()
  } catch (error) {
    console.error('路由守卫错误:', error)
    // 发生错误时，允许继续导航，防止白屏
    next()
  }
})

// 全局后置钩子
router.afterEach((to, from) => {
  console.log('路由导航完成:', to.path)
  // 可以在这里添加页面统计等操作
})

// 全局错误处理
router.onError((error) => {
  console.error('路由错误:', error)
})

export default router